package hjw.com.controller;

import hjw.com.entity.Cart;
import hjw.com.entity.Comment;
import hjw.com.entity.LargeFile;
import hjw.com.entity.User;
import hjw.com.service.CartServiceImpl;
import hjw.com.service.CommentServiceImpl;
import hjw.com.service.LargeFileServiceImpl;
import hjw.com.service.UserServiceImpl;
import hjw.com.util.PackJsn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>Project:Academic - UserController
 *
 * @author IvanWei玮 -- maste
 * @version 1.0
 * @DataTime 2025/1/20 15:29
 * @since 1.8
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(UserController.class);
    /**
     * 密码最小长度
     */
    private static final int MIN_PASSWORD_LENGTH = 6;
    /**
     * 密码最大长度
     */
    private static final int MAX_PASSWORD_LENGTH = 10;
    private static final Random RANDOM = new Random();
    private final UserServiceImpl userDao;
    private final LargeFileServiceImpl largeFileDao;
    private final PasswordEncoder passwordEncoder;
    private final CommentServiceImpl commentDao;

    @Autowired
    public UserController(UserServiceImpl userDao, LargeFileServiceImpl largeFileDao, PasswordEncoder passwordEncoder, CommentServiceImpl commentDao, CartServiceImpl cartDao) {
        this.userDao = userDao;
        this.largeFileDao = largeFileDao;
        this.passwordEncoder = passwordEncoder;
        this.commentDao = commentDao;
    }

    /**
     * 用户获取评价信息
     */
    @GetMapping("/comment")
    public String getComment(){
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号id
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("uid", user.getId());
        List<Comment> comments = commentDao.getComment(map);
        if(comments == null || comments.isEmpty()){
            return PackJsn.pack(200,"商品暂无评价");
        }
        return PackJsn.pack(200, "商品评价", comments);
    }

    /**
     * 用户评价商品
     */
    @PostMapping("/addComment")
    public String addComment(@RequestBody Map<String, Object> map) {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号id
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        map.put("nickname", user.getNickname());
        map.put("img", user.getImg());
        map.put("uid", user.getId());
        logger.info("获取评价"+map);

        int i = commentDao.addComment(map);
        return i==0 ? PackJsn.pack(200, "评价失败"):PackJsn.pack(200, "评价成功", null);
    }
    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public String getInfo() {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }

        Map<String, Object> map = new HashMap<>(4);
        map.put("img", user.getImg());
        map.put("role", user.getRole());
        map.put("name", user.getNickname());
        map.put("account", user.getAccount());

        return PackJsn.pack(200, "用户信息", map);
    }
    /**
     * 提交：带上请求头token
     * @return 用户地址 电话 姓名
     */
    @GetMapping("/shipInfo")
    public String getUserShipInfo(){
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        Map<String, Object> map = new HashMap<>(3);
        map.put("nickname", user.getNickname());
        map.put("phone", user.getPhone());
        map.put("addr", user.getAddr());
        return PackJsn.pack(200, "用户发货信息", map);
    }

    @PostMapping("/updatePwd")
    public String updatePwd(String oldPassword, String newPassword){
//        新密码输入校验放到前端
        logger.info("输入的原始密码：" + oldPassword);
        logger.info("输入的新密码：" + newPassword);
        if (oldPassword == null || oldPassword.isEmpty() ||newPassword == null || newPassword.isEmpty()){
            return PackJsn.pack(203, "密码不能为空");
        }
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        logger.info("修改密码");
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "更新失败，登录过期", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        //校验当前用户密码是否相匹配
        if (!passwordEncoder.matches(oldPassword, user.getPassword())){
            logger.info("旧密码错误");
            return PackJsn.pack(203, "旧密码输入有误");
        }

        //校验当前用户修改后的密码是否雷同
        if (passwordEncoder.matches(newPassword,  user.getPassword())) {
            return PackJsn.pack(203, "新密码与最近使用的密码雷同，请重新输入");

        }
        //密码长度规范
        if (newPassword.length() < MIN_PASSWORD_LENGTH){
            return PackJsn.pack(203, "密码长度不能小于6位");
        }

        if (newPassword.length() > MAX_PASSWORD_LENGTH){
            return PackJsn.pack(203, "密码长度不能大于10位");
        }
        //装配到数据的容器
        Map<String, Object> map = new HashMap<>(2);
        map.put("password", newPassword);
        map.put("id", user.getId());
        int updated = userDao.update(map);
        if (updated == 0){
            logger.info("密码修改失败");
            return PackJsn.pack(203, "密码修改失败");
        }
        logger.info("密码修改成功");
        return PackJsn.pack(200, "修改成功");
    }
    /**
     * 用于修改用户的头像信息
     * @return String
     */
    @PostMapping("/updatePic")
    public String updateImg(@RequestParam(value = "mypic", required = false)MultipartFile myfile) throws IOException {

        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        if (myfile == null || myfile.isEmpty()){
            logger.info("头像上传失败");
            return PackJsn.pack(203, "头像上传失败",user.getImg());
        }
        logger.info("修改用户头像信息");
        int delete = largeFileDao.delete(user.getImg());
        if (delete == 0){
            logger.info("删除用户头像失败");
            return PackJsn.pack(203, "修改用户头像失败");
        }
        LargeFile largeFile = new LargeFile();
        String picId = user.getImg();
        largeFile.setId(picId.substring(0,picId.length()-1) + RANDOM.nextInt(10));
        largeFile.setFilename(myfile.getOriginalFilename());
        largeFile.setContent(myfile.getBytes());
        int add = largeFileDao.add(largeFile);
        if (add == 0){
            logger.info("修改用户头像失败");
            return PackJsn.pack(203, "修改用户头像失败",user.getImg());
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("img", largeFile.getId());
        map.put("id", user.getId());
        //更新用户的图片id返回对象
        int updated = userDao.update(map);
        return PackJsn.pack(200, "修改用户头像成功", largeFile.getId());
    }

    @PostMapping("/updateShip")
    public String updateShip(@RequestBody Map<String,Object> map){
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        logger.info("修改用户收货信息:"+map);
        String nickname = (String) map.get("nickname");
        if (nickname == null || nickname.isEmpty()){
            map.remove("nickname");
        }
        String phone = (String) map.get("phone");
        if (phone == null || phone.isEmpty()){
            map.remove("phone");
        }
        String addr = (String) map.get("addr");
        if (addr == null || addr.isEmpty()){
            map.remove("addr");
        }
        map.put("id", user.getId());
        int updated = userDao.update(map);
        if (updated == 0){
            logger.info("修改收货信息失败");
            return PackJsn.pack(203, "修改收货信息失败");
        }
        logger.info("修改收货信息成功");
        return PackJsn.pack(200, "修改收货信息成功");
    }

    @GetMapping("/getMyComment")
    public String getMyComment(){
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null){
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        logger.info("获取用户信息成功");
        //获取账号
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null){
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        Map<String, Object> map = new HashMap<>(1);
        map.put("uid", user.getId());
        System.out.println(map);
        List<Comment> comments = commentDao.getComment(map);
        if (comments == null || comments.isEmpty()){
            logger.info("用户未评论过");
            return PackJsn.pack(203, "无评论数据");
        }
        return PackJsn.pack(200, "获取用户评论成功", comments);
    }


}
